<?php
/**
 * 用户列表管理
 * 相对路径: adm/usli.php
 * 作者: 15058593138@qq.com
 */

// 查询用户
if (isset($_GET['act']) && $_GET['act'] === 'search') {
    $keyword = isset($_POST['keyword']) ? safeStr($_POST['keyword']) : '';
    $page = isset($_POST['page']) ? intval($_POST['page']) : 1;
    
    $db = new DB();
    $userTable = TB_PREFIX . 'user';
    
    $where = "1=1";
    if (!empty($keyword)) {
        $where .= " AND `手机号` LIKE '%{$keyword}%'";
    }
    
    $sql = "SELECT COUNT(*) FROM `{$userTable}` WHERE {$where}";
    $total = $db->getCount($sql);
    
    $offset = ($page - 1) * PAGE_SIZE;
    $sql = "SELECT * FROM `{$userTable}` WHERE {$where} ORDER BY `id` DESC LIMIT {$offset}, " . PAGE_SIZE;
    $list = $db->getAll($sql);
    
    $db->close();
    jsonMsg(1, '查询成功', ['list' => $list, 'total' => $total, 'page' => $page]);
}

// 修改密码
if (isset($_GET['act']) && $_GET['act'] === 'editpwd') {
    $id = isset($_POST['id']) ? intval($_POST['id']) : 0;
    $newPwd = isset($_POST['new_pwd']) ? $_POST['new_pwd'] : '';
    
    if ($id <= 0 || empty($newPwd)) {
        jsonMsg(0, '参数错误');
    }
    
    if (strlen($newPwd) < 6) {
        jsonMsg(0, '密码长度不能少于6位');
    }
    
    $db = new DB();
    $userTable = TB_PREFIX . 'user';
    $pwdHash = pwdHash($newPwd);
    
    $result = $db->update($userTable, ['密码' => $pwdHash], "`id` = {$id}");
    $db->close();
    
    if ($result) {
        jsonMsg(1, '密码修改成功');
    } else {
        jsonMsg(0, '密码修改失败');
    }
}

// 删除用户
if (isset($_GET['act']) && $_GET['act'] === 'delete') {
    $id = isset($_POST['id']) ? intval($_POST['id']) : 0;
    
    if ($id <= 0) {
        jsonMsg(0, '参数错误');
    }
    
    $db = new DB();
    $userTable = TB_PREFIX . 'user';
    
    // 不能删除管理员
    $user = $db->getRow("SELECT * FROM `{$userTable}` WHERE `id` = {$id}");
    if ($user && $user['VXID'] === 'admin') {
        jsonMsg(0, '不能删除管理员账户');
    }
    
    $result = $db->delete($userTable, "`id` = {$id}");
    $db->close();
    
    if ($result) {
        jsonMsg(1, '删除成功');
    } else {
        jsonMsg(0, '删除失败');
    }
}

// 批量删除
if (isset($_GET['act']) && $_GET['act'] === 'batchdel') {
    $ids = isset($_POST['ids']) ? $_POST['ids'] : '';
    
    if (empty($ids)) {
        jsonMsg(0, '请选择要删除的用户');
    }
    
    $idsArr = explode(',', $ids);
    $db = new DB();
    $userTable = TB_PREFIX . 'user';
    
    $success = 0;
    foreach ($idsArr as $id) {
        $id = intval($id);
        if ($id <= 0) continue;
        
        // 检查是否是管理员
        $user = $db->getRow("SELECT * FROM `{$userTable}` WHERE `id` = {$id}");
        if ($user && $user['VXID'] === 'admin') {
            continue;
        }
        
        if ($db->delete($userTable, "`id` = {$id}")) {
            $success++;
        }
    }
    
    $db->close();
    jsonMsg(1, "成功删除{$success}个用户");
}

require_once './inc/head.php';
?>

<div class="container">
    <div class="search-bar">
        <input type="text" id="searchKeyword" class="form-control" placeholder="搜索手机号" style="flex:2">
        <button class="btn btn-primary" onclick="searchUsers(1)">查询</button>
        <button class="btn btn-danger" onclick="batchDelete()">批量删除</button>
    </div>
    
    <div class="table-wrapper">
        <table class="table">
            <thead>
                <tr>
                    <th><input type="checkbox" id="checkAll" onclick="toggleCheckAll()"></th>
                    <th>ID</th>
                    <th>手机号</th>
                    <th>角色</th>
                    <th>注册时间</th>
                    <th>最后登录</th>
                    <th>操作</th>
                </tr>
            </thead>
            <tbody id="userList">
                <tr>
                    <td colspan="7" style="text-align:center;">加载中...</td>
                </tr>
            </tbody>
        </table>
    </div>
    
    <div id="pagination"></div>
</div>

<script>
    let currentPage = 1;
    
    // 搜索用户
    function searchUsers(page) {
        currentPage = page || 1;
        const keyword = document.getElementById('searchKeyword').value;
        
        ajax('admin.php?do=usli&act=search', {keyword: keyword, page: currentPage}, function(res) {
            if (res.code === 1) {
                renderUsers(res.data.list);
                renderPagination(res.data.total);
            } else {
                toast(res.msg, 'error');
            }
        });
    }
    
    // 渲染用户列表
    function renderUsers(data) {
        const tbody = document.getElementById('userList');
        
        if (data.length === 0) {
            tbody.innerHTML = '<tr><td colspan="7" style="text-align:center;">暂无数据</td></tr>';
            return;
        }
        
        let html = '';
        data.forEach(user => {
            const isAdmin = user.VXID === 'admin';
            html += `<tr>
                <td><input type="checkbox" class="user-check" value="${user.id}" ${isAdmin ? 'disabled' : ''}></td>
                <td>${user.id}</td>
                <td>${user.手机号}</td>
                <td>${isAdmin ? '<span style="color:#dc3545;">管理员</span>' : '普通用户'}</td>
                <td>${user.添加时间 || '-'}</td>
                <td>${user.最后登录 || '-'}</td>
                <td>
                    <button class="btn btn-primary btn-sm" onclick="editPwd(${user.id})">改密</button>
                    ${!isAdmin ? `<button class="btn btn-danger btn-sm" onclick="deleteUser(${user.id})">删除</button>` : ''}
                </td>
            </tr>`;
        });
        
        tbody.innerHTML = html;
    }
    
    // 渲染分页
    function renderPagination(total) {
        const paginationDiv = document.getElementById('pagination');
        paginationDiv.innerHTML = pagination(currentPage, total, 'searchUsers');
    }
    
    // 全选/取消全选
    function toggleCheckAll() {
        const checkAll = document.getElementById('checkAll');
        const checks = document.querySelectorAll('.user-check');
        checks.forEach(check => {
            if (!check.disabled) {
                check.checked = checkAll.checked;
            }
        });
    }
    
    // 修改密码
    function editPwd(id) {
        showModal('修改密码', `
            <div class="form-group">
                <label>新密码</label>
                <input type="password" id="newPwd" class="form-control" placeholder="请输入新密码（至少6位）">
            </div>
        `, [
            {text: '取消', class: 'btn-secondary', onclick: 'closeModal()'},
            {text: '确定', class: 'btn-primary', onclick: `doEditPwd(${id})`}
        ]);
    }
    
    function doEditPwd(id) {
        const newPwd = document.getElementById('newPwd').value;
        if (!newPwd) {
            toast('请输入新密码', 'error');
            return;
        }
        
        closeModal();
        ajax('admin.php?do=usli&act=editpwd', {id: id, new_pwd: newPwd}, function(res) {
            if (res.code === 1) {
                toast(res.msg, 'success');
            } else {
                toast(res.msg, 'error');
            }
        });
    }
    
    // 删除用户
    function deleteUser(id) {
        showModal('确认删除', '<p>确定要删除该用户吗？</p>', [
            {text: '取消', class: 'btn-secondary', onclick: 'closeModal()'},
            {text: '确定', class: 'btn-danger', onclick: `doDelete(${id})`}
        ]);
    }
    
    function doDelete(id) {
        closeModal();
        ajax('admin.php?do=usli&act=delete', {id: id}, function(res) {
            if (res.code === 1) {
                toast(res.msg, 'success');
                searchUsers(currentPage);
            } else {
                toast(res.msg, 'error');
            }
        });
    }
    
    // 批量删除
    function batchDelete() {
        const checks = document.querySelectorAll('.user-check:checked');
        if (checks.length === 0) {
            toast('请选择要删除的用户', 'error');
            return;
        }
        
        const ids = Array.from(checks).map(c => c.value).join(',');
        
        showModal('批量删除', `<p>确定要删除选中的 ${checks.length} 个用户吗？</p>`, [
            {text: '取消', class: 'btn-secondary', onclick: 'closeModal()'},
            {text: '确定', class: 'btn-danger', onclick: `doBatchDelete('${ids}')`}
        ]);
    }
    
    function doBatchDelete(ids) {
        closeModal();
        showLoading();
        ajax('admin.php?do=usli&act=batchdel', {ids: ids}, function(res) {
            hideLoading();
            if (res.code === 1) {
                toast(res.msg, 'success');
                searchUsers(currentPage);
            } else {
                toast(res.msg, 'error');
            }
        });
    }
    
    // 页面加载
    window.onload = function() {
        searchUsers(1);
    };
</script>

<?php require_once './inc/foot.php'; ?>